# req res 都要写模型，有了模型，就可以校验转换，fn 的参数也可以复用这些模型
# 多个模型间类似 CSS 语法

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserBase(BaseModel):
    username: str
    email: EmailStr
    full_name: str | None = None


class UserIn(UserBase):
    password: str


class UserOut(UserBase):
    pass


class UserInDB(UserBase):
    hashed_password: str


def fake_password_hasher(raw_password: str):
    return "salt " + raw_password


def fake_save_user(user_in: UserIn):
    hashed_password = fake_password_hasher(user_in.password)
    # **user_in.dict() 过时了 用 **user_in.model_dump()，**作用和 JS 的 {...formData, id:'xxx} 类似
    user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
    return user_in_db


# 按 UserOut 返回，没有 password，而且自动转 json
@app.post("/user/", response_model=UserOut)
async def create_user(user_in: UserIn):
    user_saved = fake_save_user(user_in)
    print(
        user_saved)  # user_saved:username='string' email='user@example.com' full_name='string' hashed_password='salt string'
    return user_saved  # 这里实际返回的是 {"username": "string","email": "user@example.com","full_name": "string"}
